﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace Chat 
{
    public class UsernameTakenException : Exception
    {
        public UsernameTakenException() : base("Username already taken") {    }
    }

    public class Client
    {
        private const int kChatPort = 999;

        public static Connection Connect(String serverAddress, String username, IMessageDelegate messageDelegate)
        {
            Socket socket = null;
            Connection result = null;
            try
            {

                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                socket.Connect(serverAddress, kChatPort);

                DataPacket.Send(socket, username);

                String response = DataPacket.Receive(socket);

                if (response.Equals("OK"))
                {
                    result = new Chat.Connection(socket, username, messageDelegate);
                }
                else if (response.Equals("Exists"))
                {
                    throw new UsernameTakenException();
                }

            }
            catch (SocketException)
            {
                return null;
            }

            return result;
        }
    }
}
